package com.university.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.university.infrastructure.Result;
import com.university.utility.ObjectUtils;

import java.util.List;

/**
 * 所有Controller的基类
 */
public abstract class BaseController {
    protected <Src, Target> Result ok(Src src, Class<Target> clazz) {
        Target target = ObjectUtils.convert(src, clazz);

        if (target != null) {
            return Result.success(target);
        }

        return Result.failure(404, "对象为空");
    }

    protected <Src, Target> Result ok(List<Src> src, Class<Target> clazz) {
        List<Target> target = ObjectUtils.convert(src, clazz);

        if (target == null || target.size() == 0) {
            return Result.failure(404, "对象列表为空");
        }

        return Result.success(target);
    }

    protected <Src, Target> Result ok(IPage<Src> src, Class<Target> clazz) {
        IPage<Target> target = ObjectUtils.convert(src, clazz);

        if (target == null || target.getSize() == 0) {
            return Result.failure(404, "对象列表为空");
        }

        return Result.success(target);
    }

    protected <Target> Result ok(Target obj) {
        if (obj != null) {
            return Result.success(obj);
        }

        return Result.failure(404, "对象不存在！");
    }

    protected Result ok() {
        return Result.success();
    }

    protected Result fail(String message) {
        return Result.failure(404, message);
    }

}
